package com.citygis.transferdata.config.dataSource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @ClassName: MasterDataSourceConfig 
 * @Description: TODO
 * @author: liuzg
 * @Date: 2021/8/31 9:32
 * @Version: v1.0
 */
@Configuration
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {

    // 精确 master 目录，以便跟踪其他数据源隔离
    static final String PACKAGE = "com.citygis.transferdata.api.source1.dao";
    static final String MAPPER_LOCATION = "classpath*:mapper/master/*.xml";

    @Primary
    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource userDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    //标志这个Bean如果在多个同类Bean候选时，该Bean优先被考虑。多数据源配置的时候，
    // 必须要有一个主数据源，用@Primary标志该Bean。标志这个Bean如果在多个同类Bean候选时，
    // 该Bean优先被考虑。多数据源配置的时候，必须要有一个主数据源，用@Primary标志该Bean。
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(userDataSource());
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCallSettersOnNulls(true);   //当mybaits字段返回值为空时,输出null,不配置则不输出.
        sessionFactory.setConfiguration(configuration);
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MasterDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

}
